package com.example.fish.controller;

import com.example.fish.controller.ex.LoginException;
import com.example.fish.pojo.User;
import com.example.fish.pojo.UserInfo;
import com.example.fish.service.UserInfoService;
import com.example.fish.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/info")
public class UserInfoController extends BaseController {
    @Autowired
    private UserInfoService userInfoService;

    /***
     *  用户信息查询
     * @return Userinfo实体类
     */
    @GetMapping("/showInfo")
    public JsonResult<UserInfo> showInfo(HttpSession session){
        User user = (User)session.getAttribute("user");
        if (user == null){
//            用户信息不存在
            throw new LoginException("用户信息查询失败");
        }
        Integer userid = user.getUserid();
        UserInfo userInfo = userInfoService.getUserInfoById(userid);
        return new JsonResult<>(200,"success",userInfo);
    }

    /***
     * 用户信息更新
     * @param userInfo Userinfo实体类
     * @return int
     */
    @PostMapping("/updateInfo")
    public JsonResult<Integer> updateInfo(UserInfo userInfo, HttpSession session){
        User user =(User) session.getAttribute("user");
        Integer userid = user.getUserid();
        userInfo.setUserid(userid);
        Integer i = userInfoService.updateUserInfo(userInfo);
        return new JsonResult<>(200,"success",i);
    }

    /***
     * 接收头像
     * @param file 头像文件
     * @return int
     */
    @PostMapping("/uploadAvator")
    public JsonResult<Integer> uploadAvator(MultipartFile file, HttpSession session){
        User user = (User) session.getAttribute("user");
        Integer integer = userInfoService.updateAvatar(user.getUserid(), file);

        return new JsonResult<>(200,"success",integer);
    }

    @PostMapping("/uploadBackImg")
    public JsonResult<Integer> uploadBackImg(MultipartFile file, HttpSession session){
        User user =(User) session.getAttribute("user");
        Integer integer = userInfoService.updateBackImg(user.getUserid(),file);
        return new JsonResult<>(200,"success",integer);
    }


    @PostMapping("/getUserInfoById")
    public JsonResult<UserInfo> getUserInfoById(Integer userid){
        UserInfo userInfo = userInfoService.getUserInfoById(userid);
        return new JsonResult<>(200,"success",userInfo);
    }
}
